const parser = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const fs = require("fs");
const generator = require("@babel/generator").default;


const findApi = (arg) => {
    if (arg.type !== 'StringLiteral') return findApi(arg.left)
    return arg.value.split('?')[0]
}

function getRepeatApi(filePath) {
    return new Promise((resolve, reject) => {

        const source = fs.readFileSync(filePath, 'utf-8');

        const ast = parser.parse(source, {
            sourceType: "module",
        });

        const map = new Map();

        // 遍历ast
        traverse(ast, {
            ObjectExpression({ node }) {
                node.properties = node.properties.filter(item => {
                    const name = item.key.name // fyl
                    const { start, end } = item.loc; // 行列
                    const method = item.value.body.callee.property.name // get、post
                    const args = item.value.body.arguments // 参数

                    const api = findApi(args[0])

                    const mapKey = `${api}-${method}`
                    const mapValue = {
                        start,
                        end,
                        name,
                        api,
                    }

                    if (map.has(mapKey)) {
                        // item.key.name = 'xxx'
                        console.log('打印***str', start.line, `${mapKey} 重复`)
                        // 找到value值
                        const value = map.get(mapKey)
                        // if(value.find(item=>item.name===name))return false
                        let flag = !value.find(item => item.name === name)
                        value.push(mapValue)
                        map.set(mapKey, value)
                        return flag
                    } else {
                        map.set(mapKey, [mapValue])
                        return true
                    }
                })
            },
        });

        const { code } = generator(ast, {}, source);

        // 重写文件
        fs.writeFileSync(filePath, code)
        resolve(new Map(Array.from(map).filter(([key, value]) => value.length > 1)))
    })


}


function writeToFile(map, outputName = 'result') {
    const res = new Map()

    let txt = ''
    let sum = 0
    map.forEach((info, key) => {
        if (info.length > 1) {
            const resKey = info.map(item => item.name)
            const resValue = info[0].name
            res.set(resKey, resValue)
            sum++
            info.forEach(({ start, end, name, api }, index) => {
                if (index === 0) {
                    txt += `${api} 重复:
    第${index + 1}个位置: 开始于${start.line}行,第${start.column}列,结束于${end.line}行,第${end.column}列, ${name}\n`
                } else {
                    txt += `    第${index + 1}个位置: 开始于${start.line}行,第${start.column}列,结束于${end.line}行,第${end.column}列,${name} \n`
                }
            })

        }
    })
    txt = `重复的api数量: ${sum}\n` + txt

    fs.writeFileSync(`./${outputName}.txt`, txt);
    console.log('打印***res', res)
    return res
}

module.exports = {
    getRepeatApi,
    writeToFile
}



